package com.fyy.socket.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Scanner;

/**
 * @Author fyy
 * @Description UDP服务器端
 * @Date 2020/12/15 10:06
 */
public class AskServer {

    public static void main(String[] args) throws IOException {
        //1.创建DatagramSocket,指定接收数据的端口
        DatagramSocket socket = new DatagramSocket(8088);
        Scanner input = new Scanner(System.in);
        //2.接收数据包
        while (true){
            byte[] buf = new byte[1024]; //接收数据包的大小
            int length = buf.length;
            DatagramPacket packet = new DatagramPacket(buf,length);
            socket.receive(packet);
            String msg = new String(packet.getData(),0,packet.getLength());
            System.out.println("客户端发送的数据：" + msg);
            if("bye".equals(msg)){
                break; //客户端结束交流，关闭服务器
            }
            //发送数据给客户端
            String s = input.nextLine();
            System.out.println(s);
            packet.setData(s.getBytes());
            packet.setLength(s.getBytes().length);
            packet.setAddress(packet.getAddress());
            packet.setPort(packet.getPort());
            socket.send(packet);
        }
        //3.关闭资源
        socket.close();
    }

}
